package com.hyc.myvideo.ui.activity.my;

import android.content.Intent;
import android.os.CountDownTimer;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.TextView;

import com.acmenxd.toaster.Toaster;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.hyc.myvideo.R;
import com.hyc.myvideo.data.api.constants.Constants;
import com.hyc.myvideo.data.api.model.BaseResult;
import com.hyc.myvideo.data.api.model.Code;
import com.hyc.myvideo.data.api.model.UserInfo;
import com.hyc.myvideo.ui.base.BaseFActivity;
import com.hyc.myvideo.widget.ClearEditText;

import butterknife.BindView;
import butterknife.OnClick;


/**
 * 注册
 * @author gyb
 * @version 1.0
 * @created 2017/07/14
 */
public class RegisteredActivity extends BaseFActivity {
    /**
     * 账号/手机号
     */
    @BindView(R.id.r_ed_account_id)
    ClearEditText editTextAccount;
    /**
     * 获取输入的密码1
     */
    @BindView(R.id.r_ed_password_id)
    ClearEditText editTextPassword;
    /**
     * 短信验证码
     */
    @BindView(R.id.r_ed_verification_code_id)
    ClearEditText editTextCode;
    /**
     * 邀请人
     */
    @BindView(R.id.r_ed_invite)
    ClearEditText editTextInvite;

    /**
     * 倒计时显示
     */
    @BindView(R.id.r_t_verification_id)
    TextView setTextViewVerification;

    @BindView(R.id.r_check_id)
    CheckBox checkBox;
    /**
     * 提交按钮
     */
    @BindView(R.id.r_bu_id)
    Button buttonSubmit;
    TimeCount timeCount = new TimeCount(60000, 1000);
    private  Code code = null;
    @Override
    public int getContentViewId() {
        return R.layout.activity_registered;
    }

    @Override
    protected void initView() {
        setLeftBtnClick(true, getStr(R.string.home_head_registered));
        editTextCode.addTextChangedListener(textWatcherC);
        editTextAccount.addTextChangedListener(textWatcher);
        setButtonSubmit(false);
        setTextViewVerification(false, "获取验证码");
//        checkBox.setOnCheckedChangeListener(changeListener);
    }

    @Override
    protected void initData() {

    }

    /***
     * 注册成功回调返回参数
     * @param param
     */
    private void setCallback(final String... param) {
        setResult(Constants.RESULT_CODE, new Intent().putExtra("account", param[0]));
        this.finish();
    }
    @Override
    protected void oNext(String r, String method) {
        /**获取短信返回*/
        if (method.equalsIgnoreCase(Constants.API_SMS)) {
            BaseResult<Code> result = JSONObject.parseObject(r, new TypeReference<BaseResult<Code>>(){});
            if(result.isCode()){
                this.code = result.getResult();
            }
        }
        /**注册返回*/
        if (method.equalsIgnoreCase(Constants.API_REG)) {
            BaseResult<UserInfo> result = JSONObject.parseObject(r, new TypeReference<BaseResult<UserInfo>>(){});
            if (result.isCode()) {
                //成功
                Toaster.show(Gravity.CENTER, result.getMsg());
                setCallback(getBEDstr(editTextAccount));
            } else {
                //失败
                Toaster.show(Gravity.CENTER, result.getMsg());
            }
        }
    }

    @Override
    protected void oError() {

    }

    @OnClick({R.id.r_t_verification_id, R.id.r_bu_id})
    public void onClicks(View view) {
        switch (view.getId()) {
            /**获取验证码*/
            case R.id.r_t_verification_id:
                timeCount.start();//计时开始
                api.requestPhoneCode(getBEDstr(editTextAccount));
                break;
            /**确定*/
            case R.id.r_bu_id:
                if(code.getSms_code().equalsIgnoreCase(getBEDstr(editTextCode))){
                    api.userRegistered(getBEDstr(editTextAccount), getBEDstr(editTextPassword), getBEDstr(editTextCode), getBEDstr(editTextInvite));
                }else{
                    Toaster.show("验证码错误!");
                }
                break;
        }
    }

    /**
     * 定义一个倒计时的内部类
     */
    class TimeCount extends CountDownTimer {
        public TimeCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }
        @Override
        public void onTick(long millisUntilFinished) {
            /**按钮不可点击*/
            long length = millisUntilFinished / 1000;
            setTextViewVerification(false, length + " S");
        }

        @Override
        public void onFinish() {
            setTextViewVerification(true, "重新发送");
        }
    }

    /***
     * 设置验证码状态值
     * @param isClickable
     * @param str
     */
    private void setTextViewVerification(boolean isClickable, String str) {
        if (setTextViewVerification != null) {
            setTextViewVerification.setText(str);
            setTextViewVerification.setClickable(isClickable);
            if (isClickable) {
                setTextViewVerification.setBackgroundResource(R.drawable.button_shape_5);
            } else {
                setTextViewVerification.setBackgroundResource(R.drawable.button_shape_5_1);
            }
        }
    }

    /***
     * 设置提交按钮状态
     * @param isClickable
     */
    private void setButtonSubmit(boolean isClickable) {
        buttonSubmit.setClickable(isClickable);
        checkBox.setChecked(isClickable);
        if (isClickable) {
            buttonSubmit.setBackgroundResource(R.drawable.button_shape_35);
        } else {
            buttonSubmit.setBackgroundResource(R.drawable.button_shape_35_1);
        }
    }

    /***
     * 监听手机输入
     */
    TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if (num >= 11) {
                setTextViewVerification(true, "获取验证码");
                if (num >= 4 && getBEDstr(editTextAccount).length() >= 11 && getBEDstr(editTextPassword).length() >= 6) {
                    setButtonSubmit(true);
                }
            } else {
                checkBox.setChecked(false);
                setTextViewVerification(false, "获取验证码");
            }
            timeCount.cancel();//关闭


        }
    };

    /***
     * 监听验证码
     */
    TextWatcher textWatcherC = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            int num = s.toString().length();
            if (num >= 4 && getBEDstr(editTextAccount).length() >= 11 && getBEDstr(editTextPassword).length() >= 6) {
                setButtonSubmit(true);
            } else {
                setButtonSubmit(false);
            }
        }
    };


    CompoundButton.OnCheckedChangeListener changeListener = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            setButtonSubmit(isChecked);
        }
    };

}
